<?php
namespace Engine;
class View
{
    const TPL_PREFIX = 'html';
    
    protected $_viewPath = '';
    
    protected $_layoutFullPath = '';
    
    protected $_disableLayout = false;
    
    protected $_vars = array();
    
    public function __construct()
    {
        $this->_viewPath = APPLICATION_DIR . '/views';
    }
    
    public function disableLayout()
    {
        $this->_disableLayout = true;
    }
    
    public function assign($key, $value = null)
    {
        if (is_array($key)) {
            foreach ($key as $k => $v) {
                $this->_vars[$k] = $v;
            }
            return $this;
        }
        
        $this->_vars[$key] = $value;
        return $this;
    }
    
    /**
     * 
     * 
     * @param string $script - path to view script
     * @param array $v
     * @return string
     * @throws \Exception 
     */
    public function renderScript($script)
    {
        $realPath = APPLICATION_DIR . '/views' . $script . '.' . self::TPL_PREFIX;
        
        if (!is_file($realPath)) {
            throw new \Exception('Script template for action is not found in path /vews');
        }
        
        ob_start();
        $v = $this->_vars;
        include $realPath;
        $out = ob_get_contents();
        ob_end_clean();
        return $out;
    }
    
    public function renderLayout($content)
    {
        if ($this->_disableLayout === false) {
            $layoutPath = $this->_viewPath . '/main.' . self::TPL_PREFIX;

            if (!is_file($layoutPath)) {
                throw new \Exception('File layout is not found in views dir');
            }
            
            ob_start();
            $v = $this->_vars;
            $v['content'] = $content;
            include $layoutPath;
            $out = ob_get_contents();
            ob_end_clean();
            return $out;
        }
        
        return $content;
    }
    
    public function render($content)
    {
        $out = '';
        if (is_array($content)) {
            unset($content['_options']);
            unset($content['layout']);
            $out = $content;
        } else {
            $out = $this->renderLayout($content);
        }
        
        return $out;
    }
}